package petertel.pbx.conf.extensions;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import petertel.pbx.utils.ConfigItem;
import petertel.pbx.utils.ParserUtils;

public class Statement {

	private ConfigItem config;

	private boolean toggle;

	private boolean displayName;

	public boolean isDisplayName() {
		return displayName;
	}

	public void setDisplayName(boolean displayName) {
		this.displayName = displayName;
	}

	public boolean isToggle() {
		return toggle;
	}

	public void setToggle(boolean toggle) {
		this.toggle = toggle;
	}

	public Statement(ConfigItem config) {
		this.config = config;
	}

	public StatementType getType() {
		return StatementType.valueOf(ParserUtils.getPairName(config.getLine())
				.toUpperCase());
	}

	public String getNameEditor() {
		return "<input value=\"" + getName() + "\" style=\"width: 100%;\"/>";
	}

	public String getName() {
		if (getType() != StatementType.EXTEN) {
			return null;
		}
		String val = ParserUtils.getPairValue(config.getLine());
		Pattern pattern = Pattern.compile("^([^,]+),[^,]+,.+$");
		Matcher matcher = pattern.matcher(val);
		if (!matcher.matches()) {
			throw new RuntimeException("Unknown format: " + val);
		}
		return matcher.group(1).trim();
	}

	public String getLabel() {
		String s = parse().group(4);
		if (s == null) {
			return null;
		} else {
			return s.trim();
		}
	}

	public String getPriority() {
		String s = parse().group(2);
		if (s == null) {
			return null;
		} else {
			return s.trim();
		}
	}

	public String getApplication() {
		String s = parse().group(5);
		if (s == null) {
			return null;
		} else {
			return s.trim();
		}
	}

	private Matcher parse() {
		String val = ParserUtils.getPairValue(config.getLine());
		if (getType() == StatementType.EXTEN) {
			int i = val.indexOf(',');
			val = val.substring(i + 1).trim();
		}
		Pattern pattern = Pattern
				.compile("^(([^,()]+)\\s*(\\(\\s*([^)]+)\\s*\\))?\\s*),(.+)$");
		Matcher matcher = pattern.matcher(val);
		if (!matcher.matches()) {
			throw new RuntimeException("Unknown format: " + val);
		}
		return matcher;
	}
}
